package com.zhiletu.collect.util;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

/**
 *
 * @Title: 图片格式转换工具
 * @Package com.zhiletu.collect.util
 * @Description: 非常牛逼的一个jdk原生图片格式转换实现，png2jpg直接压缩
 * @author zhiletu.com
 * @date 2021年3月11日
 * @version V1.0
 */
public class ImgConverter {
	public static boolean convert(String source, String formatName, String result, String resultrelease, boolean delsource) {
		File f = null;
		BufferedImage src = null;
		File nf = null;
		try {
			f = new File(source);
			if (!f.canRead()) throw new RuntimeException("对图片无读写权限" + f.getName()); // 无权限
			src = ImageIO.read(f);
			nf = new File(result);
			ImageIO.write(src, formatName, nf);

			// 为了保证释放上一文件！！！
			src = ImageIO.read(f);
			nf = new File(resultrelease);
			ImageIO.write(src, formatName, nf);

			return true;
		}
		catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		finally {
			if (delsource) {
				f.delete();
			}
			if (src != null)
				src = null;
			if (f != null)
				f = null;
			nf.delete();
		}
	}
}
